package com.mxp.influx.client.controller;

import com.mxp.influx.client.entity.api.ApiController;
import com.mxp.influx.client.entity.api.R;
import com.mxp.influx.client.service.InfluxDBService;
import com.mxp.influx.client.utils.PublicUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.influxdb.InfluxDB;
import org.influxdb.dto.Query;
import org.influxdb.dto.QueryResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author maoxp
 * @date 2024-12-24 10:29
 */
@RestController
@RequestMapping("client/query")
public class ClientQueryController extends ApiController {

    /**
     * InfluxDB服务对象
     */
    @Resource
    private InfluxDBService influxDBService;

    /**
     * 查询
     * @param database
     * @param sql
     * @return
     */
    @GetMapping
    public R query(String connectionId, String database, String sql) {
        long startTime = System.currentTimeMillis();
        InfluxDB influxDB = influxDBService.getInfluxDB(connectionId);
        if (StringUtils.isBlank(sql)) {
            return error("sql不允许为空！");
        }
        if (StringUtils.isBlank(database)) {
            database = null;
        }
        Query query = new Query(sql, database);
        QueryResult result = influxDB.query(query);
        if (result.getError() != null) {
            throw new RuntimeException(result.getError());
        }
        if (CollectionUtils.isNotEmpty(result.getResults()) && result.getResults().get(0).getError() != null) {
            throw new RuntimeException(result.getResults().get(0).getError());
        }
        long endTime = System.currentTimeMillis();
        return success(PublicUtil.getInfluxDBTableObj(result), "执行完成，用时" + (endTime - startTime) + "ms");
    }
}
